package com.webserver.core;

import com.webserver.annotations.Controller;
import com.webserver.annotations.RequestMapping;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

/**
 * 用于维护路径与业务处理方法的对应关系
 */
public class HandlerMapping {
    /**
     * key:请求路径
     * value:处理该请求的方法
     */
    private static Map<String, Method> mapping = new HashMap<>();

    static {
        initMapping();
    }

    private static void initMapping() {
        try {
            File rootDir = new File(BirdBootApplication.primarySource.getResource(".").toURI());
            File dir = new File(rootDir, "controller");//定位controller包
            if (dir.exists()) {
                File[] subs = dir.listFiles(f -> f.getName().endsWith(".class"));
                for (File sub : subs) {
                    String className = sub.getName().replaceAll(".class", "");
                    String packageName = BirdBootApplication.primarySource.getPackage().getName();
                    Class cls = Class.forName(packageName + ".controller." + className);
                    if (cls.isAnnotationPresent(Controller.class)) {
                        Method[] methods = cls.getDeclaredMethods();
                        for (Method method : methods) {
                            if (method.isAnnotationPresent(RequestMapping.class)) {
                                String value = method.getAnnotation(RequestMapping.class).value();
                                mapping.put(value, method);
                            }
                        }
                    }
                }
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据请求路径过去对应的业务处理方法
     *
     * @param uri
     * @return
     */
    public static Method getMethod(String uri) {
        return mapping.get(uri);
    }

//    public static void main(String[] args) {
//        System.out.println(mapping.size());
//        System.out.println(mapping);
//    }
}
